<template>
	<el-dialog 
		:title="isAdd ? '创建群聊' : '邀请好友'" 
		v-model="dialogVisible" 
		width="800px"
		:modal-append-to-body="false"
		:append-to-body="false"
		:close-on-click-modal="false"
		class="add-group-dialog"
		@close="onClose">
		<div class="agm-container">
			<div class="agm-l-box">
				<el-input 
					class="search-input" 
					placeholder="搜索好友" 
					v-model="searchText"
					:prefix-icon="Search">
				</el-input>
				<el-scrollbar height="450px" ref="friendScrollbar">
					<div class="friend-list">
						<div v-for="(friend,index) in displayFriends" :key="friend.id">
							<div 
								v-show="friend.nickName.includes(searchText)" 
								class="friend-item"
								@click="onSwitchCheck(friend)"
								:class="{'is-disabled': friend.disabled}">
								<el-checkbox 
									:disabled="friend.disabled" 
									v-model="friend.isCheck" 
									@click.stop>
								</el-checkbox>
								<el-avatar 
									:size="40" 
									:src="friend.headImage"
									class="friend-avatar">
									{{ friend.nickName.charAt(0) }}
								</el-avatar>
								<span class="friend-name">{{ friend.nickName }}</span>
							</div>
						</div>
						<div v-if="loading" class="loading-more">
							<el-icon class="is-loading"><Loading /></el-icon>
							<span>加载更多...</span>
						</div>
					</div>
				</el-scrollbar>
			</div>
			<div class="agm-divider">
				<el-icon><DArrowRight /></el-icon>
			</div>
			<div class="agm-r-box">
				<div class="selected-header">
					<span class="selected-title">已选择的好友</span>
					<span class="selected-count">{{ checkCount }}人</span>
				</div>
				<el-scrollbar height="450px">
					<div class="selected-list">
						<div v-for="(friend,index) in friends" :key="friend.id">
							<div v-if="friend.isCheck && !friend.disabled" class="selected-item">
								<el-avatar 
									:size="40" 
									:src="friend.headImage"
									class="friend-avatar">
									{{ friend.nickName.charAt(0) }}
								</el-avatar>
								<span class="friend-name">{{ friend.nickName }}</span>
								<el-button
									type="danger"
									:icon="Delete"
									circle
									class="remove-btn"
									@click="onRemoveFriend(friend,index)">
									<el-icon><Delete /></el-icon>
								</el-button>
							</div>
						</div>
					</div>
				</el-scrollbar>
			</div>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="onClose">取 消</el-button>
				<el-button type="danger" @click="onOk">确 定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script>
// 移除重复导入的Element Plus图标，因为它们已在main.js中全局注册
// import { Search, Delete, DArrowRight, Loading } from '@element-plus/icons-vue'
import FriendItem from '../friend/FriendItem.vue';

export default {
	name: "AddGroupMember",
	components: {
		FriendItem
	},
	setup() {
		return {
			// 移除重复注册的Element Plus图标
			// Search,
			// Delete,
			// DArrowRight,
			// Loading
		}
	},
	data() {
		return {
			searchText: "",
			friends: [],
			displayFriends: [],
			pageSize: 15,
			currentPage: 1,
			loading: false,
			dialogVisible: false,
			scrollHandler: null
		}
	},
	methods: {
		onClose() {
			// 重置状态
			this.selectedFriends = [];
			this.searchText = '';
			this.groupName = '';
			// 通知父组件关闭对话框并刷新数据
			this.$emit('close');
			// 发送额外的刷新事件，确保父组件刷新群聊列表
			this.$emit('refresh-groups');
		},
		onOk() {
			let inviteVO = {
				groupId: this.groupId,
				friendIds: [],
			}
			this.friends.forEach((f) => {
				if (f.isCheck && !f.disabled) {
					inviteVO.friendIds.push(f.id);
				}
			})
			if(this.isAdd){//新创建
				if (inviteVO.friendIds.length === 0) {
					this.$message.warning("请选择群成员");
					return;
				}
				let params = {
					ids: inviteVO.friendIds,
				}
				this.$http({
					url: '/group/create',
					method: 'POST',
					data: params
				}).then(res => {
					if(res){
						this.$message.success("创建成功！");
						// 刷新群聊列表
						this.$http({
							url: "/group/list",
							method: "get"
						}).then((groups) => {
							this.$store.commit("setGroups", groups);
							// 显式通知父组件刷新
							this.$emit('refresh-groups');
						});
						this.dialogVisible = false;
					}
				}).catch(err => {
					this.$message.error("创建失败：" + err.message);
				})
			} else {//添加人员
				if (inviteVO.friendIds.length > 0) {
					this.$http({
						url: "/group/invite",
						method: 'post',
						data: inviteVO
					}).then(() => {
						this.$message.success("邀请成功");
						this.$emit("reload");
						// 额外通知刷新群聊列表
						this.$emit('refresh-groups');
						this.dialogVisible = false;
					}).catch(err => {
						this.$message.error("邀请失败：" + err.message);
					})
				} else {
					this.$message.warning("请选择要邀请的好友");
				}
			}
		},
		onRemoveFriend(friend, index) {
			friend.isCheck = false;
		},
		onSwitchCheck(friend) {
			if (!friend.disabled) {
				friend.isCheck = !friend.isCheck
			}
		},
		initFriendsList() {
			this.friends = [];
			this.$store.state.friendStore.friends.forEach((f) => {
				let friend = JSON.parse(JSON.stringify(f));
				let m = this.members.filter((m) => !m.quit)
					.find((m) => m.userId == f.id);
					
				if(friend.isdel) {
					friend.disabled = true;
					friend.isCheck = true;
				} else {
					if (m && !this.isAdd) {
						friend.disabled = true;
						friend.isCheck = true;
					} else {
						friend.disabled = false;
						friend.isCheck = false;
					}
				}
				this.friends.push(friend);
			});
			
			this.displayFriends = this.friends.slice(0, this.pageSize);
		},
		handleScroll() {
			if (!this.$refs.friendScrollbar) return;
			
			const scrollbar = this.$refs.friendScrollbar.$refs.wrap;
			if (!scrollbar) return;
			
			const scrollHeight = scrollbar.scrollHeight;
			const scrollTop = scrollbar.scrollTop;
			const clientHeight = scrollbar.clientHeight;
			
			if (scrollHeight - scrollTop - clientHeight < 30 && !this.loading) {
				this.loadMore();
			}
		},
		bindScrollEvent() {
			this.$nextTick(() => {
				if (this.$refs.friendScrollbar && this.$refs.friendScrollbar.$refs.wrap) {
					const scrollbar = this.$refs.friendScrollbar.$refs.wrap;
					this.scrollHandler = this.handleScroll.bind(this);
					scrollbar.addEventListener('scroll', this.scrollHandler);
				}
			});
		},
		unbindScrollEvent() {
			if (this.$refs.friendScrollbar && this.$refs.friendScrollbar.$refs.wrap && this.scrollHandler) {
				const scrollbar = this.$refs.friendScrollbar.$refs.wrap;
				scrollbar.removeEventListener('scroll', this.scrollHandler);
				this.scrollHandler = null;
			}
		},
		loadMore() {
			if (this.loading) return;
			
			const start = this.currentPage * this.pageSize;
			if (start >= this.friends.length) return;
			
			this.loading = true;
			setTimeout(() => {
				const end = start + this.pageSize;
				const newFriends = this.friends.slice(start, end);
				this.displayFriends = [...this.displayFriends, ...newFriends];
				this.currentPage++;
				this.loading = false;
			}, 100);
		},
		resetLoad() {
			this.currentPage = 1;
			this.displayFriends = this.friends.slice(0, this.pageSize);
		}
	},
	props: {
		visible: {
			type: Boolean,
			default: false
		},
		groupId: {
			type: String,
			default:'0',
		},
		members: {
			type: Array,
			default: () => []
		},
		isAdd:{
			type: Boolean,
			default: false
		}
	},
	computed: {
		checkCount() {
			return this.friends.filter((f) => f.isCheck && !f.disabled).length;
		}
	},
	watch: {
		visible: {
			immediate: true,
			handler(val) {
				this.dialogVisible = val;
				if (val) {
					this.$nextTick(() => {
						this.initFriendsList();
						this.bindScrollEvent();
					});
				} else {
					this.unbindScrollEvent();
				}
			}
		},
		dialogVisible(val) {
			if (!val) {
				this.unbindScrollEvent();
				this.$emit('update:visible', false);
				this.$emit('close');
			}
		},
		searchText() {
			this.resetLoad();
		}
	},
	beforeUnmount() {
		this.unbindScrollEvent();
	},
	unmounted() {
		this.unbindScrollEvent();
	}
}
</script>

<style lang="scss">
.add-group-dialog {
	:deep(.el-dialog) {
		border-radius: 8px;
		overflow: hidden;
		
		.el-dialog__header {
			margin: 0;
			padding: 20px 24px;
			border-bottom: 1px solid var(--el-border-color-lighter);
			
			.el-dialog__title {
				font-size: 18px;
				font-weight: 600;
				color: var(--el-text-color-primary);
			}
		}
		
		.el-dialog__body {
			padding: 24px;
		}
		
		.el-dialog__footer {
			padding: 16px 24px;
			border-top: 1px solid var(--el-border-color-lighter);
			background: var(--el-bg-color-page);
		}
	}
}

.agm-container {
	display: flex;
	gap: 24px;
	min-height: 500px;
	
	.agm-l-box, .agm-r-box {
		flex: 1;
		display: flex;
		flex-direction: column;
		background: var(--el-bg-color-page);
		border-radius: 8px;
		border: 1px solid var(--el-border-color-lighter);
		
		.search-input {
			margin-bottom: 16px;
			
			:deep(.el-input__wrapper) {
				border-radius: 8px;
				box-shadow: 0 0 0 1px var(--el-border-color-lighter);
				
				&:hover {
					box-shadow: 0 0 0 1px var(--el-color-primary-light-7);
				}
				
				&.is-focus {
					box-shadow: 0 0 0 1px var(--el-color-primary);
				}
			}
		}
		
		.friend-list, .selected-list {
			padding: 8px;
		}
		
		.friend-item, .selected-item {
			display: flex;
			align-items: center;
			padding: 12px;
			border-radius: 8px;
			cursor: pointer;
			transition: all 0.3s;
			
			&:hover {
				background: var(--el-color-primary-light-9);
			}
			
			&.is-disabled {
				cursor: not-allowed;
				opacity: 0.6;
			}
			
			.el-checkbox {
				margin-right: 12px;
			}
			
			.friend-avatar {
				margin-right: 12px;
				background: var(--el-color-primary-light-7);
				color: var(--el-color-primary);
				font-weight: bold;
			}
			
			.friend-name {
				flex: 1;
				font-size: 14px;
				color: var(--el-text-color-primary);
			}
			
			.remove-btn {
				opacity: 0;
				transition: all 0.3s;
			}
			
			&:hover .remove-btn {
				opacity: 1;
			}
		}
	}
	
	.agm-divider {
		display: flex;
		align-items: center;
		color: var(--el-color-primary);
		font-size: 24px;
	}
}

.selected-header {
	padding: 16px;
	border-bottom: 1px solid var(--el-border-color-lighter);
	display: flex;
	align-items: center;
	justify-content: space-between;
	
	.selected-title {
		font-size: 16px;
		font-weight: 500;
		color: var(--el-text-color-primary);
	}
	
	.selected-count {
		padding: 2px 8px;
		background: var(--el-color-primary-light-9);
		color: var(--el-color-primary);
		border-radius: 12px;
		font-size: 14px;
	}
}

.loading-more {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 16px;
	color: var(--el-text-color-secondary);
	font-size: 14px;
	
	.el-icon {
		margin-right: 8px;
	}
}

.dialog-footer {
	display: flex;
	justify-content: flex-end;
	gap: 12px;
	
	.el-button {
		padding: 8px 24px;
		font-size: 14px;
	}
}
</style>